import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/live/live_detail_entity.dart';
import 'package:ball_lion/server/api/live_api.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import 'package:ball_lion/entity/other/image_upload_result_entity.dart';
import 'package:ball_lion/server/http/dio_utils.dart';
import 'package:ball_lion/utils/image_utils.dart';
import 'package:ball_lion/widgets/select_bottomsheet.dart';

class LiveCreateLogic extends GetxController {
  final TextEditingController titleController = TextEditingController();
  final Rx<String> _title = "".obs;
  bool validTitle = false;
  FocusNode focus = FocusNode();
  DateTime? _time;
  String? cover;
  int _sportsId = 1;

  bool get allDone {
    return validTitle && _time != null && cover != null;
  }

  String get title => _title.value;
  DateTime? get time => _time;
  int get sportsId => _sportsId;

  set sportsId(int value) {
    _sportsId = value;
    update();
  }

  set time(DateTime? value) {
    _time = value;
    update();
  }

  set title(String value) {
    _title.value = value;
    update();
  }

  String? validateTitle(String? value) {
    if (value!.length >= 4 && value.length <= 15) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        validTitle = true;
        update();
      });
    } else {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        validTitle = false;
        update();
      });
    }
    return null;
  }

  Future chooseCover() async {
    final result =
        await Get.bottomSheet(const SelectBottomSheet(['拍照', '从手机相册选择']));
    if (result == 0) {
      var photo = await ImageUtils.pickPhotoFromCamera();
      if (photo == null) {
        return;
      }
      String path = photo.path;
      List<ImageUploadResultEntity>? result =
          await DioUtils.uploadImage([path], 'live');
      if (result != null) cover = result.first.url;
    } else if (result == 1) {
      List<AssetEntity>? images = await ImageUtils.pickPhotoFromGallery();
      if (images.noValue) return;
      File? file = await images!.first.file;
      if (file != null) {
        List<ImageUploadResultEntity>? result =
            await DioUtils.uploadImage([file.path], 'live');
        if (result != null) cover = result.first.url;
      }
    }
    update();
  }

  Future create() async {
    LiveDetailEntity? result = await LiveApi.createLive(
        title, time!.toString(), cover!,
        sportsId: sportsId);
    if (result != null) {
      Toast.text("创建成功");
      Get.back();
    } else {
      // Toast.text("创建失败，请稍后重试");
    }
  }
}
